import provinces from "@/uni_modules/vk-uview-ui/libs/address/provinces.json";
import citys from "@/uni_modules/vk-uview-ui/libs/address/citys.json";
import areas from "@/uni_modules/vk-uview-ui/libs/address/areas.json";
export default {
	data() {
		return {
			adr:{}
		}
	},
	methods:{
		// 智能识别省市区
		regionDiscern(addressText){
			// 街道地址
			let address = "";
			// 省
			let province = {};
			// 市
			let city = {};
			// 区
			let area = {};
			if (!addressText) return { code: -1, msg: "地址文本不能为空" };
			addressText.trim(); // 去除前后空格
			// 省
			// 1.先找出省份，通过匹配前面两个字(中国34个省份中，前面两个字不会重复)
			let firstTwoKey = addressText.substring(0, 2); //字符串开始的两个字符
			// 所在省的下标
			let provinceIndex = -1;
			
			for (let i = 0; i < provinces.length; i++) {
				let { code, name } = provinces[i];
				if (name.indexOf(firstTwoKey) == 0) {
					province = { code, name };
					provinceIndex = i;
					break;
				}
			}
			if (provinceIndex == -1) return { code: -1, msg: `省份【${firstTwoKey}】没有找到，请输入正确的地址` };
			console.log(provinceIndex,3333)
			// 获取市
			let citysArr = citys[provinceIndex];
			console.log(citysArr,'对应市编码')
			// 所在市的下标
			let cityIndex = -1;
			
			for (let i = 0; i < citysArr.length; i++) {
				let { name, code } = citysArr[i];
				// 除去最后一个 市 字
				let cityName = name.substr(0, name.length - 1);
				// 用城市的名字去匹配 addressText 地址
				if (addressText.indexOf(cityName) > -1) {
					city = { code, name };
					cityIndex = i;
					break;
				}else{
					if(name.indexOf("省直辖县级行政区划")>-1||name.indexOf("自治区直辖县级行政区划")>-1){
						city = { code, name };
						cityIndex = i;
						break;
					}
				}
			}
			console.log(cityIndex)
			if (cityIndex == -1) return { code: -1, msg: `地级市没有找到，请输入正确的地址` };
			// 区
			let areasArr = areas[provinceIndex][cityIndex];
			console.log(areasArr)
			// 所在区的下标
			let areaIndex = -1;
			for (let i = 0; i < areasArr.length; i++) {
				let { code, name } = areasArr[i];
				// 区名(县名)为2个字时，不会简写，如蓉县
				let reg = name;
				if (name.length > 2) reg += `|${name.substr(0, name.length - 1)}`;
				// 查找地址中是否存在该区名
				let areaRegExp = new RegExp(reg);
				if (addressText.search(areaRegExp) > -1) {
					area = { code, name };
					// 详情地址
					address = addressText.replace(new RegExp(reg), "{{~}}").split("{{~}}")[1];
					areaIndex = i;
					break;
				}
			}
			if (areaIndex == -1) return { code: -1, msg: "县级市没有找到，请输入正确的地址" };
			let formatted_address = `${province.name}${city.name}${area.name}${address}`;
			let res = {
				code: 0,
				msg: "ok",
				data: {
					province, // 省
					city,	// 市
					area,	// 区
					address, // 街道地址
					formatted_address, // 完整格式化地址
				}
			};
			console.log(res)
			return res;
		},
	}
}